package file;

import javax.swing.table.AbstractTableModel;
import java.io.File;
import java.util.Date;

public class FileTableModel extends AbstractTableModel {
    private File[] files;
    private String[] columnNames = {"名称", "大小", "类型", "修改日期"};

    public FileTableModel() {
        setDirectory(new File(System.getProperty("user.home")));
    }

    public void setDirectory(File directory) {
        this.files = directory.listFiles();
        fireTableDataChanged();
    }

    @Override
    public int getRowCount() {
        return files != null ? files.length : 0;
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if (files == null) return null;

        File file = files[rowIndex];
        switch (columnIndex) {
            case 0:
                return file.getName();
            case 1:
                return file.length() + " 字节";
            case 2:
                return file.isDirectory() ? "文件夹" : "文件";
            case 3:
                return new Date(file.lastModified());
            default:
                return null;
        }
    }
}